package cn.xiuxian.dao.impl;

import cn.xiuxian.dao.IAccDao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class AccDaoImpl implements IAccDao {
    @Override
    public void saveSalary(Integer fromId, Integer whereId, Double salary) {
        Connection  connection = null;
        PreparedStatement preparedStatement = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/dy?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
            String username = "root";
            String password = "root";
            connection = DriverManager.getConnection(url,username,password);
            connection.setAutoCommit(false);
            String sql = "update  t_acc  set  balance = balance - ?  where id = ?";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setDouble( 1,salary);
            preparedStatement.setInt(2,fromId);

            preparedStatement.executeUpdate();        //自动commit
            preparedStatement.clearParameters();
       //     System.out.println(10/0);
            preparedStatement.setDouble(1,-salary);
            preparedStatement.setInt(2,whereId);

            preparedStatement.executeUpdate();

            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            if(preparedStatement != null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
